package com.icangya.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icangya.DAO.IDomainDAO;
import com.icangya.Utils.JSONUtils;
import com.icangya.Value.FootBall;
import com.icangya.Value.StaticValue;
import com.icangya.common.config.PageViewsThread;
import com.icangya.domain.*;
import com.icangya.service.*;
import com.icangya.wxpay.utils.MD5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.icangya.Value.FootBall.FOOT_PAGE_ROW;
import static com.icangya.Value.StaticValue.ADMIN_USER_SESSION;


@CrossOrigin
@RestController
@RequestMapping(value = "/admin/adminFund")
public class AdminController {

    @Autowired
    private IDomainService iDomainService;
    @Autowired
    private IDomainDAO iDomainDAO;
    @Autowired
    private IAdminUserService iAdminUserService;
    @Autowired
    private IMoneyService iMoneyService;
    @Autowired
    private IFootUserService iFootUserService;
    @Autowired
    private IAdvertService iAdvertService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @RequestMapping(value = "/advertsham")
    public JSONObject advertsham(@RequestParam int status) {
        String str = "";
        PageViewsThread th = new PageViewsThread();
        if (status == 0){
            str = "虚假自动增加浏览量已关闭";
            th.flag = false;
        }else if (status == 1){
            str = "虚假自动增加浏览量已开启";
            th.flag = true;
        }else {
            str = "虚假自动增加浏览量设置错误";
        }
        logger.info(status+"=================================");
        return JSONUtils.getRoot(0,"success",str);
    }


    @RequestMapping(value = "/selectDomains")
    public JSONObject selectDomains() {
        List<DomainDO> domainList = null;
        try {
            domainList = iDomainService.selectDomains();
        } catch (Exception e) {
            return JSONUtils.getRoot(0,"fail",e.getMessage());
        }
        JSONObject jsonObject = null;
        JSONArray jsonArray = new JSONArray();
        for (DomainDO domainDO : domainList){
            jsonObject = new JSONObject();
            jsonObject.put("id",domainDO.getId());
            jsonObject.put("domainUrl",domainDO.getDomainUrl());
            jsonObject.put("isavailable",domainDO.getIsavailable());
            jsonArray.add(jsonObject);
            jsonObject = null;

        }
        return JSONUtils.getRoot(0,"success",jsonArray);
    }

    @RequestMapping(value = "/getDomain")
    public JSONObject getDomain() {
        List<DomainDO> domainlist = null;
        try {
            domainlist = iDomainService.getDoamin();
        } catch (Exception e) {
            return JSONUtils.getRoot(0,"fail",e.getMessage());
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",domainlist.get(0).getId());
        jsonObject.put("DomainUrl",domainlist.get(0).getDomainUrl());
        jsonObject.put("isavailable",domainlist.get(0).getIsavailable());
        return JSONUtils.getRoot(0,"success",jsonObject);
    }
    @RequestMapping(value = "/insertDomain", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
    public JSONObject insertDomain(@RequestParam String domainUrl) {

        if(domainUrl.indexOf(" ")!=-1){
            return JSONUtils.getRoot(1,"fail","存在非法字符!(不允许空格)");
        }
        if(domainUrl==null || "".equals(domainUrl)){
            return JSONUtils.getRoot(1,"fail","域名不能为空！");
        }

        DomainDO domainDO = new DomainDO();
        domainDO.setDomainUrl(domainUrl);
        domainDO.setIsavailable("0");

        try {
            iDomainService.saveDomain(domainDO);
            return JSONUtils.getRoot(0,"success","1");
        } catch (Exception e) {
            return JSONUtils.getRoot(1,"fail",e.getMessage());
        }
    }

    @RequestMapping(value = "/updateDomain", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
    public JSONObject updateDomain(@RequestParam Long id ,@RequestParam String isavailable) {

        if ("0".equals(isavailable) || "1".equals(isavailable) || "2".equals(isavailable)){
            DomainDO domainDO = iDomainDAO.get(id);
            domainDO.setIsavailable(isavailable);
            try {
                iDomainService.updateDoamin(domainDO);
                return JSONUtils.getRoot(0,"success","1");
            } catch (Exception e) {
                return JSONUtils.getRoot(1,"fail",e.getMessage());
            }
        }else{
            return JSONUtils.getRoot(1,"fail","参数异常！");
        }

    }

    @RequestMapping(value = "exitLogin")
    public JSONObject  exitLogin(HttpSession session){

        // 销毁session
        session.removeAttribute(ADMIN_USER_SESSION);
        return JSONUtils.getRoot(0,"success",null);
    }

    //后台登录
    @RequestMapping(value = "login")
    public JSONObject login(@RequestParam String name, @RequestParam String passWord, HttpSession session){

        //正则匹配密码为4-10位的数字（管理员）
        Pattern p = Pattern.compile("(\\d{4,10})");
        Matcher m = p.matcher(name);

        //正则匹配密码为6-12位的数字和字母（管理员）
        Pattern p1 = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$");
        Matcher m1 = p1.matcher(passWord);

        logger.info("前端传进来的密码："+passWord);

        if (m.matches() && m1.matches()) {
            //密码加密(规则：密码+proxy_key，使用md5加一次密)
//            passWord = MD5Util.toMD5(passWord + StaticValue.PROXY_KEY).toUpperCase();
            try {
                passWord = MD5Utils.getMD5Upper(passWord + StaticValue.REGISTER_KEY);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            JSONObject jsonObject=new JSONObject();
            Admin admin=iAdminUserService.login(name,passWord,session);

            if(admin==null){
                //不存在该用户
                return JSONUtils.getRoot(1,"fail","不存在该用户");
            }else{
                if(passWord.equals(admin.getPassWord())){
                    /*登录成功,将用户写入session中*/
                    session.setAttribute(ADMIN_USER_SESSION,admin);
                    return  JSONUtils.getRoot(0,"success",jsonObject);
                }else{
                    //密码不正确
                    return JSONUtils.getRoot(1,"fail","密码不正确");
                }
            }

        }else{
//            1，密码不能全部是数字
//            2，密码不能全部是字母
//            3，密码必须是数字或字母
            return JSONUtils.getRoot(1,"fail","账号或密码长度不符合，账号的长度是4-10的数字，密码的长度为6-12位的数字加字母");
        }
//        if (m1.matches()) {
//            //密码加密(规则：密码+REGISTER_KEY，使用md5加一次密)（管理员）
////            passWord = MD5Util.toMD5(passWord + StaticValue.REGISTER_KEY).toUpperCase();
//            try {
//                passWord = MD5Utils.getMD5Upper(passWord + StaticValue.REGISTER_KEY);
//            } catch (NoSuchAlgorithmException e) {
//                e.printStackTrace();
//            }
//            logger.info("加密后的密码："+passWord);
//            JSONObject jsonObject=new JSONObject();
//
//            Admin admin=iAdminUserService.login(name,passWord,session);
//            if(admin==null){
//                //不存在该用户
//                jsonObject.put("error_code",UPDATE_ERROR_CODE);
//                jsonObject.put("msg","不存在该用户");
//            }else{
//                if(passWord.equals(admin.getPassWord())){
//                    /*登录成功*/
//                    jsonObject.put("error_code",SUCCESS);
//                    jsonObject.put("msg","登录成功");
//                    /**将用户写入session中*/
//                    session.setAttribute(ADMIN_USER_SESSION,admin);
//                }else{
//                    //密码不正确
//                    jsonObject.put("error_code", UPDATE_ERROR_CODE);
//                    jsonObject.put("tip", "密码不正确");
//                }
//            }
//            return  JSONUtils.getRoot(0,"success",jsonObject);
//
//        }else{
////            1，密码不能全部是数字（管理员）
////            2，密码不能全部是字母（管理员）
////            3，密码必须是数字或字母（管理员）
//            return JSONUtils.getRoot(1,"fail","账号或密码长度不符合，账号的长度是4-10的数字，密码的长度为6-12位的数字加字母");
//        }


//        return  iAdminUserService.login(name,passWord,session);

    }

    //获取登录后用户信息
    @RequestMapping(value = "loginIndex")
    public JSONObject loginIndex(HttpSession session){
        Admin admin= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息
//        if(admin==null)
//            return JSONUtils.getRoot(1,"fail","用户不能为空");
        return JSONUtils.getRoot(0,"success",admin.getUserName());
//        return JSONUtils.getRoot(0,"success",admin);
    }

    //修改密码
    @RequestMapping(value = "setAccountName")
    public JSONObject setAccountName(@RequestParam String password,@RequestParam String passWord2,HttpSession session){

        if(passWord2=="" || password =="")
            return JSONUtils.getRoot(1,"fail","参数不能为空");

        //正则匹配密码为6-12位的数字和字母
        Pattern p1 = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$");
        Matcher m1 = p1.matcher(passWord2);
        Matcher m = p1.matcher(password);

        if (m.matches()) {
            //密码加密(规则：密码+proxy_key，使用md5加一次密)
            try {
                password = MD5Utils.getMD5Upper(password + StaticValue.REGISTER_KEY);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }else{
//            1，密码不能全部是数字
//            2，密码不能全部是字母
//            3，密码必须是数字或字母
            return JSONUtils.getRoot(1,"fail","旧密码长度不符合 ，密码的长度为6-12位的数字加字母");
        }

        if (m1.matches()) {
            //密码加密(规则：密码+proxy_key，使用md5加一次密)
            try {
                passWord2 = MD5Utils.getMD5Upper(passWord2 + StaticValue.REGISTER_KEY);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }else{
//            1，密码不能全部是数字
//            2，密码不能全部是字母
//            3，密码必须是数字或字母
            return JSONUtils.getRoot(1,"fail","新密码长度不符合 ，密码的长度为6-12位的数字加字母");
        }
//        Admin admin=  iAdminDAO.getAdminById(1); //测试
        Admin admin= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息
        return iAdminUserService.setAccountName(admin.getUserName(),password,passWord2);


    }

     //获取系统每天的收入
    @RequestMapping(value = "getGainRecord")
    public  JSONObject getGainRecord(@RequestParam String startTime,@RequestParam String endTime){

            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//
                System.out.println("start" + startTime + "..............end" + endTime);
                Date start = sdf.parse(startTime);
                Date end = sdf.parse(endTime);

                GainRecord gainRecord = iMoneyService.getGainRecordTime(new Timestamp(start.getTime()), new Timestamp(end.getTime()));
                if (gainRecord != null){
                    return JSONUtils.getRoot(0, "success", gainRecord);
                }
                return JSONUtils.getRoot(1, "fail", null);
             } catch (ParseException e) {
                 e.printStackTrace();
                return JSONUtils.getRoot(1, "fail", "");
        }
    }

    //获取系统所有的收入信息
    @RequestMapping(value = "getGainRecordAll")
    public JSONObject getGainRecordAll(@RequestParam int startPage){
        JSONObject jsonObject=iMoneyService.getGainRecordAll(startPage);
        if(jsonObject!=null)
            return JSONUtils.getRoot(0,"success",jsonObject);
        return JSONUtils.getRoot(1,"fail",null);
    }
    /**
     * 获取轮播图信息
     * @return
     */
    @RequestMapping(value = "getCarouselFigure")
    @ResponseBody
    public JSONObject getCarouselFigure(){
        logger.info("===================getCarouselFigure=====================");
        return JSONUtils.getRoot(0,"success",iAdminUserService.getAllCarouselFigure());
    }


     // 添加轮播图
    @RequestMapping(value = "setCarouselFigure")
    public JSONObject setCarouselFigure(HttpServletRequest request, HttpServletResponse response, MultipartFile file, @RequestParam String imgContent) throws IOException {
        if(imgContent.equals(null)){
            imgContent="广州心上人科技有限公司";
        }

        //上传的目录地址
        String uploadDir= request.getSession().getServletContext().getRealPath("/")+"carouse/";
        //如果目录不存在，自动创建文件夹
        File dir=new File(uploadDir);
        if(!dir.exists()){
            dir.mkdir();
        }
        String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        //上传文件名
        String filename= UUID.randomUUID()+suffix;

        //服务器端保存的文件对象
        File serverFile=new File(uploadDir+filename);
        //将上传的文件写入到服务器端文件内
        try {
            file.transferTo(serverFile);
        } catch (IOException e) {
            e.printStackTrace();//上传失败
            return JSONUtils.getRoot(1,"fail","上传失败");
        }

        CarouselFigure carouselFigure=  iAdminUserService.setCarouselFigure(new CarouselFigure("carouse/"+filename,imgContent));


        response.sendRedirect("/hAdmin/mailbox.html" );//返回到轮播图页面
//        response.sendRedirect("http://192.168.0.118:8020/hAdmin/mailbox.html" );
        return JSONUtils.getRoot(0,"success",carouselFigure.getId());
    }


    /**
     * 删除轮播图信息
     * @param cid
     */
    @RequestMapping(value = "deleteCarouselById")
    public JSONObject deleteCarouselByCid(long cid){

        boolean result=   iAdminUserService.delCarouseByCid(cid);
        if(result)
            return JSONUtils.getRoot(0,"success","删除成功");
        return JSONUtils.getRoot(1,"fail","删除失败");

    }

    /**
     * 获取用户详情
     * @return
     */
    @RequestMapping(value = "getUserAll")
    public JSONObject getUserAll(@RequestParam int  startPage,HttpSession session){

        Admin admin= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息
        JSONObject jsonObject=iAdminUserService.getUserByProxy(startPage,1);//系统后台查询所有用户
        if(jsonObject!=null)
            return JSONUtils.getRoot(0,"success",jsonObject);

        return JSONUtils.getRoot(1,"fail",null);
    }

    /**
     *  根据用户id,查询用户信息
     * @param uid
     * @return
     */
    @RequestMapping(value = "checkUserById")
    public JSONObject checkUserById(@RequestParam long uid,HttpSession session){

        Admin admin= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息
       JSONObject jsonObject=iAdminUserService.checkUserById(uid,1);
//        JSONObject jsonObject=iAdminUserService.checkUserById(uid,admin.getUid());
        if(jsonObject!=null)
            return JSONUtils.getRoot(0,"success",jsonObject);

        return JSONUtils.getRoot(1,"fail",null);
    }

    /**
     * 设置中球几率，赔率
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "setFootRadio")
    public JSONObject setFootRadio(@RequestParam Map<String,String> map){

        logger.info( map.get("Map[Five_money]"));
        int fiveRadio=Integer.parseInt( map.get("Five_money"));
        int tenRadio=Integer.parseInt( map.get("Ten_money"));
        int fiftyRadio=Integer.parseInt( map.get("Fifty_money"));
        double odds=Double.parseDouble(map.get("odds"));
        double goalRadio=Double.parseDouble(map.get("goalRatio"));

        FootBall.FIVE_RADIO=getProportion(1,fiveRadio);
        FootBall.TEN_RADIO=getProportion(2,tenRadio);
        FootBall.FIFTY_RADIO=getProportion(3,fiftyRadio);
        FootBall.odds=getProportion(4,odds);//中球赔率
        FootBall.goalRatio=getProportion(5,goalRadio);//未踢中球赔率
       if(fiveRadio!=FootBall.FIVE_RADIO || tenRadio!= FootBall.TEN_RADIO || fiftyRadio!=FootBall.FIFTY_RADIO || goalRadio!=FootBall.goalRatio || odds!= FootBall.odds){
           return JSONUtils.getRoot(1,"fail",null);
       }
        return JSONUtils.getRoot(0,"success",null);
    }

    public double getProportion(int type,double radio){
        FbFootGame fbFootGame=  iAdminUserService.getFbFootGame(type);
        if(fbFootGame!=null){
            fbFootGame.setProportion(radio);// 1元抽成比例
            FbFootGame footGame= iAdminUserService.updateFbFootGame(fbFootGame);
            if(footGame!=null){
               return fbFootGame.getProportion();
            }
        }
        return 0.0;
    }
    /**
     * 获取后台设置的中球几率，赔率
     * @return
     */
    @RequestMapping(value = "getFootRadio")
    public JSONObject getFootRadio(){

        List<FbFootGame> list=iAdminUserService.getFbFootGameAll();
        if(list!=null){
            JSONObject jsonObject=new JSONObject();
            for (FbFootGame foot:list) {
                if(foot.getType()==1){
                    jsonObject.put("fiveRadio",foot.getProportion());
                    continue;
                }
                if(foot.getType()==2){
                    jsonObject.put("tenRadio",foot.getProportion());
                    continue;
                }
                if(foot.getType()==3){
                    jsonObject.put("fiftyRadio",foot.getProportion());
                    continue;
                }
                if(foot.getType()==4){
                    jsonObject.put("odds",foot.getProportion()); //中球赔率
                    continue;
                }
                if(foot.getType()==5){
                    jsonObject.put("goalRatio",foot.getProportion()); //未踢中球赔率
                    continue;
                }
            }
            return JSONUtils.getRoot(0,"success",jsonObject);
        }else {
            return JSONUtils.getRoot(1,"faild",null);
        }

    }

    //设置广告抽成
    @RequestMapping(value = "setAdvertRadio")
    public JSONObject setAdvertRadio(@RequestParam double radio){
        if(radio<1 && radio>0){
          FbFootGame fbFootGame=  iAdminUserService.getFbFootGame(0);
          if(fbFootGame!=null){
              fbFootGame.setProportion(radio);// 重新设置广告抽成
              FbFootGame footGame= iAdminUserService.updateFbFootGame(fbFootGame);
              if(footGame!=null){
                  FootBall.advertRatio=radio;
                  return JSONUtils.getRoot(0,"success",footGame.getProportion());
              }
          }
        }

      return JSONUtils.getRoot(1,"faild","参数有误");
    }

    //获取广告抽成
    @RequestMapping(value = "getAdvertRadio")
    public JSONObject getAdvertRadio(){
            FbFootGame fbFootGame=  iAdminUserService.getFbFootGame(0);
            if(fbFootGame!=null){
                return JSONUtils.getRoot(0,"success",fbFootGame.getProportion());
            }
        return JSONUtils.getRoot(1,"faild","参数有无误");
    }
    /**
     * 添加版本信息
     * @param versionNum
     * @param versionContent
     * @return
     */
    @RequestMapping(value = "setEditionInfo")
    public JSONObject setEditionInfo(@RequestParam String versionNum,@RequestParam  String versionContent){

        if("".equals(versionContent) || versionContent==null ||  "".equals(versionNum) || versionNum==null){
            return JSONUtils.getRoot(1,"faild","参数有误");
        }
        EditionInfo editionInfo=  iAdminUserService.addEdition(new EditionInfo(versionNum,versionContent,new Timestamp(new Date().getTime())));
        if(editionInfo==null)
            return JSONUtils.getRoot(1,"fail","添加失败");
        return JSONUtils.getRoot(0,"success","添加成功");
    }

    /**
     *查询所有版本信息
     * @return
     */
    @RequestMapping(value = "getEditionAll")
    public JSONObject getEditionAll(){

        return iAdminUserService.getEditionAll();
    }


    /**
     * 获取用户踢球的所有记录
     * @param openId
     * @return
     */
    @RequestMapping(value = "getKickBallByOpenId")
    public JSONObject getKickBallByOpenId(@RequestParam String openId,@RequestParam int startPage){

        if( "".equals(openId) || startPage < 1){
            return  JSONUtils.getRoot(1,"fail","参数有误");
        }
        JSONObject jsonObject=  iAdminUserService.getKickBallByOpenId(openId,startPage);
        if(jsonObject==null){
            return JSONUtils.getRoot(1,"fail","该用户没有踢球记录");
        }
        return JSONUtils.getRoot(0,"success",jsonObject);
    }

    /**
     * 用户提现的记录
     * @param openId
     * @return
     */
    @RequestMapping(value = "getCashRecord")
    public JSONObject getCashRecord(@RequestParam String openId,@RequestParam int startPage){

        if("".equals(openId) || startPage < 1){
            return  JSONUtils.getRoot(1,"fail","参数有误");
        }
        JSONObject jsonObject=iMoneyService.getCashRecord(openId,startPage);
        if(jsonObject==null) {
            return JSONUtils.getRoot(1, "fail", "用户没有提现记录");
        }
        return JSONUtils.getRoot(0,"success",jsonObject);
    }

    /**
     * 我的团队信息
     * @param uid
     * @return
     */
    @RequestMapping(value = "getProxyNum")
    public JSONObject getProxyNum( @RequestParam long uid){

        return JSONUtils.getRoot(0,"success",iFootUserService.getProxyNum(uid));
    }

    /**
     * 获取用户佣金明细
     * @param openId
     * @return
     */
    @RequestMapping(value = "getCommRecord")
    public JSONObject getCommRecord(@RequestParam String openId,@RequestParam int startPage){

        if("".equals(openId) || startPage < 1){
            return  JSONUtils.getRoot(1,"fail","参数有误");
        }
        JSONObject jsonObject=   iMoneyService.getCommRecord(openId,startPage);
        if(jsonObject==null) {
            return JSONUtils.getRoot(1, "fail", "该用户没有佣金记录");
        }

        return JSONUtils.getRoot(0,"success",jsonObject);
    }


    /**
     * 广告金记录,支出记录
     * @param openId
     * @return
     */
    @RequestMapping(value = "getExpendRecordMoney")
    public JSONObject getExpendRecordMoney(@RequestParam String openId,@RequestParam int startPage){

        if("".equals(openId) || startPage < 1){
            return  JSONUtils.getRoot(1,"fail","参数有误");
        }
        JSONObject jsonObject=iMoneyService.getExpendRecordMoney(openId,startPage);
        if(jsonObject==null) {
            return JSONUtils.getRoot(1, "fail", "该用户没有广告金支出记录");
        }
        return JSONUtils.getRoot(0,"success",jsonObject);

    }


    /**
     * 广告金记录,充值记录
     * @param openId
     * @return
     */
    @RequestMapping(value = "getRechargeRecordMoney")
    public JSONObject getRechargeRecordMoney(@RequestParam String openId,@RequestParam int startPage){

        if( "".equals(openId) || startPage < 1){
            return  JSONUtils.getRoot(1,"fail","参数有误");
        }
        JSONObject jsonObject=iMoneyService.getRechargeRecordMoney(openId,startPage);
        if(jsonObject==null) {
            return JSONUtils.getRoot(1, "fail", "该用户没有广告金充值记录");
        }
        return JSONUtils.getRoot(0,"success",jsonObject);

    }



    //设置公告提示词
    @RequestMapping(value = "setWord")
    public JSONObject setWord(@RequestParam String  cellWord){

        if("".equals(cellWord))
            return JSONUtils.getRoot(1,"faild","参数为空");

      boolean bool=  iAdminUserService.saveFbTip(new FbTip(cellWord,new Timestamp(new Date().getTime())));
          if(bool)
            return JSONUtils.getRoot(0,"success", "");
        return JSONUtils.getRoot(1,"faild","设置公告提示词错误");
    }

    //获取公告提示词
    @RequestMapping(value = "getWord")
    public JSONObject getWord(){

       FbTip fbTip= iAdminUserService.getFbTip();
       if(fbTip!=null)
        return JSONUtils.getRoot(0,"success", fbTip.getTipContent());
        return JSONUtils.getRoot(1,"falid", null);
    }

    //设置关闭系统维护
    @RequestMapping(value = "setClose")
    @ResponseBody
    public JSONObject setClose(){
        boolean bool=  iAdminUserService.setSwitch(0L);
        logger.info("setClose : "+bool);
        if(bool)
            return JSONUtils.getRoot(0,"success","设置关闭");
        return JSONUtils.getRoot(1,"fail",null);

    }
    //设置开启系统维护
    @RequestMapping(value = "setOpen")
    @ResponseBody
    public JSONObject setOpen(){
        boolean bool=  iAdminUserService.setSwitch(1L);
        logger.info("setOpen : "+bool);
        if(bool)
            return JSONUtils.getRoot(0,"success","设置打开");
        return JSONUtils.getRoot(1,"fail",null);

    }
    //获取系统维护开关信息
    @RequestMapping(value = "getSwitch")
    public JSONObject getSwitch(){

        Switch sw=  iAdminUserService.getSwitch();
        if(sw!=null)
            return JSONUtils.getRoot(0,"success",sw);
        return JSONUtils.getRoot(1,"fail",null);

    }

    //设置佣金提现关闭
    @RequestMapping(value = "setAliPayClose")
    @ResponseBody
    public JSONObject setAliPayClose(){
        boolean bool=  iAdminUserService.setAliPaySwitch(0L);
        logger.info("setAliPayClose : "+bool);
        if(bool)
            return JSONUtils.getRoot(0,"success","设置关闭");
        return JSONUtils.getRoot(1,"fail",null);

    }

    //设置佣金提现打开
    @RequestMapping(value = "setAliPayOpen")
    @ResponseBody
    public JSONObject setAliPayOpen(){
        boolean bool=  iAdminUserService.setAliPaySwitch(1L);
        logger.info("setAliPayOpen : "+bool);
        if(bool)
            return JSONUtils.getRoot(0,"success","设置打开");
        return JSONUtils.getRoot(1,"fail",null);

    }
    //获取设置佣金提现信息
    @RequestMapping(value = "getAliPaySwitch")
    public JSONObject getAliPaySwitch(){

        AliPaySwitch sw=  iAdminUserService.getAliPaySwitch();
        if(sw!=null)
            return JSONUtils.getRoot(0,"success",sw);
        return JSONUtils.getRoot(1,"fail",null);

    }
    //获取客服二维码图片
    @RequestMapping(value = "getCustomerQrCode",method = RequestMethod.POST)
    public JSONObject getCustomerQrCode(){

        CustomerImage customerImage=   iAdminUserService.getCustomerImage();
        if(customerImage!=null)
             return JSONUtils.getRoot(0,"success",customerImage);
        return JSONUtils.getRoot(1,"fail",null);
    }
    //更新客服二维码图片
    @RequestMapping(value = "setCustomerQrCode",method = RequestMethod.POST)
    public JSONObject setCustomerQrCode(HttpServletRequest request,HttpServletResponse response, MultipartFile file) throws Exception {
        if(file==null || "".equals(file)){
            return  JSONUtils.getRoot(1,"fail","参数为空");
        }
        logger.info(file+"==="+file.isEmpty());

        if (file.isEmpty()){
            response.sendRedirect("/hAdmin/code.html" );//返回到客服二维码页面
//            return  JSONUtils.getRoot(1,"fail","文件不能为空！");
        }
        try{
            //上传的目录地址
            String customerDir= request.getSession().getServletContext().getRealPath("/")+"customer/";
            //如果目录不存在，自动创建文件夹
            File dir=new File(customerDir);
            if(!dir.exists()){
                dir.mkdir();
            }
            String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //上传文件名
            String filename=  UUID.randomUUID()+suffix;

            //上传文件名
            // String filename=file.getOriginalFilename();
            //服务器端保存的文件对象
            File serverFile=new File(customerDir+filename);
            //将上传的文件写入到服务器端文件内
            file.transferTo(serverFile);
            //将上传的文件路径保存
            StaticValue.uploadImgUrl=customerDir+filename;
        CustomerImage customerImage=  iAdminUserService.saveCustomerImage(new CustomerImage("customer/"+filename,new Timestamp(new Date().getTime())));
        if(customerImage!=null){
//            response.sendRedirect("http://192.168.0.119:8020/football/src/main/resources/static/hAdmin/code.html" );//返回到客服二维码页面
            response.sendRedirect("/hAdmin/code.html" );//返回到客服二维码页面
        }

        }catch(Exception e){
            e.printStackTrace();
            return  JSONUtils.getRoot(1,"fail","上传失败");
        }
        return  JSONUtils.getRoot(1,"fail","上传失败");

    }


    /**
     * 登录后台的用户为null时跳转到错误页面
     * @param request
     * @param response
     */
    public void errorIndex(HttpServletRequest request,HttpServletResponse response){
        try{
            StringBuffer url = request.getRequestURL();
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append
                    (request.getServletContext().getContextPath()).append("/").toString();
            response.sendRedirect(tempContextUrl+"hAdmin/login.html" );//返回到轮播图页面
        }catch (IOException e){

        }

    }
    /**
     * 获取系统设置信息
     * @return
     */
    @RequestMapping(value = "getSystemSetting")
    public JSONObject getSystemSetting(){

        JSONObject jsonObject=  iAdminUserService.getSystemSetting();
        if(jsonObject!=null)
            return  JSONUtils.getRoot(0,"success",jsonObject);
        return JSONUtils.getRoot(1,"fail",null);
    }

    /**
     * 修改系统设置信息
     * @return
     */
    @RequestMapping(value = "updateSystemSetting")
    public JSONObject updateSystemSetting(@RequestParam long id,@RequestParam String updateNotice,
                                          @RequestParam String gamePlay,@RequestParam String kickSkill){


        logger.info("updateNotice========:"+updateNotice +"gamePlay:=="+gamePlay+"kickSkill:==============="+kickSkill);
        if(id<0 ){
            return JSONUtils.getRoot(1,"fail","参数不能为空");
        }
        if(updateNotice.equals("null") && gamePlay.equals("null") && kickSkill.equals("null")){
            return JSONUtils.getRoot(1,"fail","参数不能为空");
        }
        if(updateNotice.equals("") && gamePlay.equals("") && kickSkill.equals("")){
            return JSONUtils.getRoot(1,"fail","参数不能为空");
        }
        SystemSetting systemSetting=new SystemSetting(id,updateNotice,gamePlay,kickSkill);
        if(updateNotice=="")
            systemSetting.setUpdateNotice(null);

        if(gamePlay=="")
            systemSetting.setGamePlay(null);

        if(kickSkill=="")
            systemSetting.setKickSkill(null);
        logger.info("systemSetting==========="+systemSetting.toString());
        JSONObject jsonObject=  iAdminUserService.updateSystemSetting(systemSetting);
        if(jsonObject!=null)
            return  JSONUtils.getRoot(0,"success",jsonObject);
        return JSONUtils.getRoot(1,"fail","修改系统设置失败");
        //  return null;
    }

    /**
     * 添加常见问题
     * @return
     */
    @RequestMapping(value = "addCommonProblem")
    public JSONObject addCommonProblem(@RequestParam String problemTitle,@RequestParam String problemContent){

            if(problemContent.equals("") || problemContent==null || problemTitle.equals("") || problemTitle==null)
                return JSONUtils.getRoot(1,"fail","参数有误");
        CommonProblem commonProblem=  iAdminUserService.addCommonProblem(new CommonProblem(problemTitle,problemContent,new Timestamp(new Date().getTime())));
        if(commonProblem==null)
            return JSONUtils.getRoot(1,"fail",null);
        return JSONUtils.getRoot(0,"success",commonProblem);

    }

    /**
     * 获取所有的常见问题
     * @return
     */

    @RequestMapping(value = "getCommonProblem")
    public JSONObject getCommonProblem(){

        JSONObject jsonObject=  iAdminUserService.getCommonProblem();
        if(jsonObject==null)
            return JSONUtils.getRoot(1,"fail",null);
        return JSONUtils.getRoot(0,"success",jsonObject);
    }

    /**
     * 获取所有待审核中的使用支付宝提现的用户
     * @return
     */
    @RequestMapping(value = "getAliPay")
    public JSONObject getAliPay(@RequestParam int startPage){

        JSONObject jsonObject= iMoneyService.getAliPayAll(startPage);
        if(jsonObject!=null)
            return JSONUtils.getRoot(0,"success",jsonObject);

        return JSONUtils.getRoot(1,"fail",null);
    }

    /**
     * 设置体现申请审核通过
     * @param aliPayId
     * @return
     */
    @RequestMapping(value = "setApprove")
    public JSONObject setApprove(@RequestParam long aliPayId){

        boolean bool= iMoneyService.setApprove(aliPayId);

        if(bool)
            return JSONUtils.getRoot(0,"success",null);

        return JSONUtils.getRoot(1,"fail",null);
    }


    /**
     * 设置体现申请审核失败，系统拒绝提现
     * @param aliPayId
     * @return
     */
    @RequestMapping(value = "failureAudit")
    public JSONObject failureAudit(@RequestParam int aliPayId){

        boolean bool= iMoneyService.failureAudit(aliPayId);
        if(bool)
            return JSONUtils.getRoot(0,"success",null);

        return JSONUtils.getRoot(1,"fail",null);
    }

    public int[] setArray(int length){


        int[] arr=new int[100];

        for (int i=0;i<length;i++){
            arr[i]=1;
        }
        for (int i=length;i<arr.length;i++){
            arr[i]=0;
        }
        return arr;

    }


//广告
    /**
     * 查询所有用户发布的广告信息 后台 一页10条
     * @return
     */
    @RequestMapping(value="getAdvertManager")
    public JSONObject getAdvertAllManager(@RequestParam int startPage){
//startPage,FOOT_PAGE_ROW
        logger.info("==="+startPage+"===后台页码");
        JSONObject jsonObject= iAdvertService.getAdvert(startPage,FOOT_PAGE_ROW);
        if(jsonObject!=null)
            return JSONUtils.getRoot(0,"success", jsonObject);
        return JSONUtils.getRoot(1,"fail", null);
    }


    /**
     * 删除用户发布的广告
     * @param advertId
     * @return
     */
    @RequestMapping(value = "deleteAdvertById")
    public JSONObject deleteAdvert(@RequestParam long advertId) {
        boolean bool=  iAdvertService.deleteAdvertById(advertId);
        if(bool)
            return JSONUtils.getRoot(0,"success", null);

        return JSONUtils.getRoot(1,"fail", null);
    }


    //测试用户信息   查询用户信息不包含二维码
    @RequestMapping(value = "findAllUser")
    public JSONObject findAllUser(){
      List<User> list=  iFootUserService.findAllUser();
            if(list==null)
        return null;

        for (User user:list) {
            logger.info("user:============"+user.toString());
        }

        return null;
    }











}
